import i18n from '../lang/index'
import state from '@/store/state.js'

const getUrl = state.requestUrl

//获取页面传参值
function getQueryString(name) {
	var result = window.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
	if (result == null || result.length < 1) {
		console.log("ERR: 页面参数为空");
		return "";
	}
	return result[1];
};


//下载并更新app
function updateApp(wgtUrl, force) {
	if (!force) {
		plus.nativeUI.showWaiting("下载最新应用...");
	}
	let a = plus.downloader.createDownload(wgtUrl, {
		filename: "_doc/update/"
	}, function(d, status) {
		console.log(status)
		if (status == 200) {
			if (!force) {
				install(d.filename);
			} else {
				plus.nativeUI.alert("最新版本已下载，请安装更新！", function() {
					install(d.filename);
				}, "版本更新", "更新");
			}
		} else {
			plus.nativeUI.alert("下载失败！");
		}
		plus.nativeUI.closeWaiting();
	}).start();
}
//安装资源文件
function install(path) {
	plus.runtime.install(path, {}, function() {

	}, function(e) {

	});
}

//格式化日期
function formatDate(n, t) {
	var i, r, u;
	if (!n)
		return "";
	i = n;
	typeof n == "string" && (i = n.indexOf("/Date(") > -1 ? new Date(parseInt(n.replace("/Date(", "").replace(")/", ""),
		10)) : new Date(Date.parse(n.replace(/-/g, "/").replace("T", " ").split(".")[0])));
	r = {
		"M+": i.getMonth() + 1,
		"d+": i.getDate(),
		"h+": i.getHours(),
		"m+": i.getMinutes(),
		"s+": i.getSeconds(),
		"q+": Math.floor((i.getMonth() + 3) / 3),
		S: i.getMilliseconds()
	};
	/(y+)/.test(t) && (t = t.replace(RegExp.$1, (i.getFullYear() + "").substr(4 - RegExp.$1.length)));
	for (u in r) new RegExp("(" + u + ")").test(t) && (t = t.replace(RegExp.$1, RegExp.$1.length == 1 ? r[u] : ("00" +
		r[u]).substr(("" + r[u]).length)));
	return t
}
// "yyyy-MM-dd hh:mm:sss"

// 格式化日期，如月、日、时、分、秒保证为2位数
function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n;
}
// 参数number为毫秒时间戳，format为需要转换成的日期格式
function formatTimes(number, format) {
	let time = new Date(number * 1000)
	let newArr = []
	let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
	newArr.push(time.getFullYear())
	newArr.push(formatNumber(time.getMonth() + 1))
	newArr.push(formatNumber(time.getDate()))

	newArr.push(formatNumber(time.getHours()))
	newArr.push(formatNumber(time.getMinutes()))
	newArr.push(formatNumber(time.getSeconds()))

	for (let i in newArr) {
		format = format.replace(formatArr[i], newArr[i])
	}
	return format;
}

function getToken() {
	// 	var timestamp = new Date().getTime();
	// 	var token = timestamp + parseInt(Math.floor(Math.random() * 9 + 1)).toString() + 'sjcx';
	// 	return encMe(token, 'sjcx###***');
	// console.log(uni.getStorageSync("dzpt_login"))
	if (uni.getStorageSync("huashanghui_token")) {
		return JSON.parse(uni.getStorageSync("huashanghui_token")).token
	} else {
		return "";
	}
}

function Percentage(ab) {
	var data = parseInt(ab * 100);
	console.log(data);
	return data
}


//不需要token的
function fech(url, postData, succ, fail) {
	let header = {}
	header['Content-Type'] = 'application/x-www-form-urlencoded'
	header['token'] = ''
	let lang = state.lang_type
	header['language'] = lang
	uni.request({
		url: getUrl + url,
		data: postData,
		dataType: 'json',
		header,
		method: 'POST',
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}

//需要token的
function postAjax(url, postData, succ, fail) {
	let header = {}
	header['token'] = state.loginInfo.token || ''
	header['Content-Type'] = 'application/x-www-form-urlencoded'
	let lang = state.lang_type
	header['language'] = lang
	uni.request({
		url: getUrl + url,
		data: postData,
		dataType: 'json',
		header,
		method: 'POST',
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			// console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}


//get
function getAjax(url, postData, succ, fail) {
	let header = {}
	header['token'] = state.loginInfo.token || ''
	header['Content-Type'] = 'application/x-www-form-urlencoded'
	let lang = uni.getStorageSync('lang') || 'traditional'
	header['language'] = lang
	uni.request({
		url: getUrl + url,
		data: postData,
		dataType: 'json',
		header,
		method: 'GET',
		success: function(data) {
			succ(data.data)
		},
		fail: function(data) {
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}
//需要token的,跳过审核封装
function postFu(url, postData, succ, fail) {
	let header = {}
	header['token'] = getToken()
	header['Content-Type'] = 'application/x-www-form-urlencoded'
	header['wxapp_id'] = '10001'
	header['business'] = 1
	let resp = {
		wxapp_id: '10001',
		token: getToken()
	}
	let respobj = Object.assign(resp, postData);
	uni.request({
		url: getUrl + url,
		data: respobj,
		dataType: 'json',
		header,
		method: 'POST',
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			// console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}

function getAjaxx(url, postData, action, succ, fail) {
	var data1 = formatDate(new Date(), "yyyy-MM-dd hh:mm:sss");
	let time1 = new Date(Date.parse(data1.replace(/-/g, "/"))).getTime();
	let date = time1 / 1000; //精确到秒就可以了，再除以1000即可
	// console.log( getToken())
	// console.log(date)
	// console.log(getUrl)
	uni.request({
		url: getUrl + url,
		data: postData,
		dataType: 'json',
		method: 'POST',
		header: {
			token: getToken(),
			action: action,
			format: 'json',
			charset: 'utf-8',
			version: '1.0',
			timestamp: date
		},
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	})
}

function wsCmd(action, userinfo, vehid, pram, callback) {

	console.log("连接信息" + JSON.stringify(userinfo));
	//实例化
	var ws = mysocket(userinfo, function(res) {
		callback(res);
		console.log(res);
	});
	mysocket[0].page.analysis(action, vehid, pram);

	// 	
	// 	setTimeout(function() {
	// 		mysocket.page.analysis(action, vehid, pram);
	// 	}, 2000)
}

//用户登录后用的上传图片封装
function uploadIMG(url, imgs, succ) {
	let header = {}
	// console.log(uni.getStorageSync('loginInfo'));	
	header['token'] = uni.getStorageSync('loginInfo').token
	let lang = uni.getStorageSync('lang')
	if (lang) {
		if (lang == 'chs') {
			header['language'] = 'traditional'
		} else {
			header['language'] = 'english'
		}
	} else {
		header['language'] = 'traditional'
	}
	// console.log(JSON.stringify(header))
	uni.uploadFile({
		url: getUrl + url,
		filePath: imgs,
		name: 'file',
		header,
		success: function(uploadFileRes) {
			succ(uploadFileRes);
		},
		fail: function(data) {
			console.log("失败" + JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	});
}

//上传文件
function uploadwenj(url, imgs, succ) {
	uni.uploadFile({
		url: getUrl + url,
		filePath: imgs,
		name: 'file',
		formData: {
			user: 'test',
			wxapp_id: '10001',
		},
		success: function(uploadFileRes) {
			succ(uploadFileRes);
		},
		fail: function(data) {
			console.log("失败" + JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	});
}

// function uploadIMG(url, imgs, succ) {
// 	let header = {}
// 	header['JLSC'] = getToken()
// 	console.log(header)
// 	uni.uploadFile({
// 		url: getUrl + url,
// 		filePath: imgs,
// 		name: 'file',
// 		header,
// 		formData: {
// 			files: imgs
// 		},
// 		success: function(uploadFileRes) {
// 			succ(uploadFileRes);
// 		},
// 		fail: function(data) {
// 			console.log("失败" + JSON.stringify(data));
// 			uni.showToast({
// 				icon: 'none',
// 				title: '网络连接出错，请重试'
// 			});
// 		}
// 	});
// }

function addUserInfo(userInfo) {
	let users = {
		account: userInfo.account,
		password: userInfo.password
	};
	uni.setStorageSync('cwg_userInfos', JSON.stringify(users));
}

function getUserInfo() {
	let ret = uni.getStorageSync('cwg_userInfos');
	if (!ret) {
		ret = false;
	}
	return JSON.parse(ret);
}

function log(msg) {
	if (store.state.debug) {
		// console.log(JSON.stringify(msg))
	}
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
//获取个推clientid
function client() {
	var id = '';
	uni.getProvider({
		service: 'push',
		success: function(res) {
			// console.log(res.provider)
			// 个推的名称为 igexin
			uni.subscribePush({
				provider: 'igexin',
				success: function(res) {
					id = res.clientid
					// console.log('success:' + JSON.stringify(res));
				}
			});
		}
	});
	return id
}

function forMatNum(num) {
	return num < 10 ? '0' + num : num + '';
}

function initDays(year, month) {
	let totalDays = new Date(year, month, 0).getDate();
	let dates = [];
	for (let d = 1; d <= totalDays; d++) {
		dates.push(forMatNum(d));
	};
	return dates;
}

function initPicker(start, end, mode = "date", step = 1) {
	let initstartDate = new Date(start);
	let endDate = new Date(end);
	let startYear = initstartDate.getFullYear();
	let startMonth = initstartDate.getMonth();
	let endYear = endDate.getFullYear();
	let years = [],
		months = [],
		days = [],
		hours = [],
		minutes = [];
	let totalDays = new Date(startYear, startMonth, 0).getDate();
	for (let s = startYear; s <= endYear; s++) {
		years.push(s + '');
	};
	for (let m = 1; m <= 12; m++) {
		months.push(forMatNum(m));
	};
	for (let d = 1; d <= totalDays; d++) {
		days.push(forMatNum(d));
	}
	for (let h = 0; h < 24; h++) {
		hours.push(forMatNum(h));
	}
	for (let m = 0; m < 60; m += step) {
		minutes.push(forMatNum(m));
	}
	if (mode == "date") {
		return {
			years,
			months,
			days
		}
	} else if (mode == "dateTime") {
		return {
			years,
			months,
			days,
			hours,
			minutes
		}
	} else if (mode == "time") {
		return {
			hours,
			minutes
		}
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	postAjax: postAjax,
	getAjax: getAjax,
	getAjaxx: getAjaxx,
	getToken: getToken,
	log: log,
	getUserInfo: getUserInfo,
	addUserInfo: addUserInfo,
	getQueryString: getQueryString,
	uploadIMG: uploadIMG,
	formatDate: formatDate,
	updateApp: updateApp,
	wsCmd: wsCmd,
	client: client,
	forMatNum: forMatNum,
	initDays: initDays,
	initPicker: initPicker,
	formatTimes: formatTimes,
	fech: fech,
	Percentage: Percentage,
	uploadwenj: uploadwenj,
	postFu: postFu
}